var gradRender = {
    vector: null,
    source: null,
    classSeries:null,
    classColors:null,
    init: function (city) {

        var defaultStyle = new ol.style.Style({
            fill: new ol.style.Fill({
                color: 'rgba(255, 255, 255, 0.3)'

            }),
            stroke: new ol.style.Stroke({
                color: 'rgba(0, 255, 0, 1)',
                width: 1
            }),
            text: new ol.style.Text({
                font: '12px Calibri,sans-serif',
                fill: new ol.style.Fill({
                    color: '#000'
                }),
                stroke: new ol.style.Stroke({
                    color: '#fff',
                    width: 3
                })
            })
        });
        this.baseVector = new ol.layer.Vector({
            style: defaultStyle,
            source: new ol.source.Vector({
                url: '../../assets/newMap/data/mapdata/county/' + city + '00.json',
                format: new ol.format.GeoJSON({
                    defaultDataProjection: 'EPSG:4326',
                    featureProjection: 'EPSG:3857'
                })
            })
        });
        map.addLayer(this.baseVector);
        this.vector = new ol.layer.Vector({
            source: this.getSource(city)
        })
        map.addLayer(this.vector);
    },
    getSource: function (id) {
        var url = '../../assets/newMap/data/mapdata/county/' + id + '00.json';
        var source = new ol.source.Vector({
            id: 'county',
            format: new ol.format.GeoJSON({
                defaultDataProjection: 'EPSG:4326',
                featureProjection: 'EPSG:3857'
            }),
            loader: function (extent, resolution, projection) {
                gradRender.countryPopVals = new Array();
                $.ajax({
                    url:url,
                    type:'GET',
                    async:false,
                    success:function (data) {
                        var zoom = map.getView().getZoom();
                        var radius = 1e6 / Math.pow(2, zoom - 2);
                        var features = source.getFormat().readFeatures(data);
                        var newid = id + '00';
                        $.ajax({
                            url:'/newMap/initMapData',
                            data:{
                                currentMap: 'clusterMap',
                                city: newid,
                                level: '3'
                            },
                            type:'POST',
                            async:false,
                            success:function (info) {
                                debugger
                                var text = JSON.stringify(info);
                                var countryPopVals = new Array();
                                var list = info.result.mapDataList;
                                features.forEach(function (feature) {
                                    var name = feature.N.name;
                                    var zoneNumber = feature.N.id;
                                    var count = gradRender.getCount(list, name, zoneNumber);
                                    feature.set('count', count, false);
                                    countryPopVals.push(count);
                                })
                                gradRender.beginRender(countryPopVals);
                            }
                        });
                        source.addFeatures(features);
                    }
                })
            }
        });
        source.set('id', 'county');
        this.source = source;
        return source;
    },
    beginRender: function (countryPopVals) {
        this.getAndSetClassesFromData(countryPopVals, this.getClassNum(), this.getMethod());
        this.vector.setStyle(this.setStyle);
        //map.addLayer(this.vector);
    },
    //获取和设置Class从geojson数据
    getAndSetClassesFromData: function (data, numclasses, method) {
        // var colorFrom = 'FFFFFF';
        // var colorTo = 'FF0000';
        var colorFrom = 'FFFFFF';
        //color end to
        var colorTo = '1A8B16';
        var serie = new geostats(data);
        var legenLabel = "";
        if (method === "method_EI") {
            serie.getClassEqInterval(numclasses);
            methodLabel = "Equal Interval";
            methodLabel = "等间距";
        } else if (method === "method_Q") {
            serie.getClassQuantile(numclasses);
            methodLabel = "Quantile";
            methodLabel = "分位数";
        } else if (method === "method_SD") {
            serie.getClassStdDeviation(numclasses);
            methodLabel = "Standard Deviation ";
            methodLabel = "标准差";
        } else if (method === "method_AP") {
            serie.getClassArithmeticProgression(numclasses);
            methodLabel = "等差数";
        } else if (method === "method_GP") {
            serie.getClassGeometricProgression(numclasses);
            methodLabel = "Geometric Progression ";
        } else if (method === "method_CJ") {
            serie.getClassJenks(numclasses);
            methodLabel = "Class Jenks";
        } else {
            alert("error: no such method.")
        }
        var colors_x = chroma.scale([colorFrom, colorTo]).colors(numclasses)

        serie.setColors(colors_x);
        document.getElementById('legend').innerHTML = serie.getHtmlLegend(colors_x, "分级渲染</br>渲染模式:" + methodLabel, 1);
        gradRender.classSeries = serie;
        gradRender.classColors = colors_x;
    },
    setStyle: function (feat, res) {
        var currVal = parseFloat(feat.get("count"));
        var bounds = gradRender.classSeries.bounds;
        var numRanges = new Array();
        for (var i = 0; i < bounds.length - 1; i++) {
            numRanges.push({
                min: parseFloat(bounds[i]),
                max: parseFloat(bounds[i + 1])
            });
        }
        var classIndex = gradRender.verifyClassFromVal(numRanges, currVal);
        var polyStyleConfig = {
            stroke: new ol.style.Stroke({
                color: 'rgba(255, 0, 0,0.3)',
                width: 1
            })
        };
        var textStyleConfig = {};
        var label = res < 5000 ? feat.get('NAME') : '';
        if (classIndex !== -1) {
            polyStyleConfig = {
                stroke: new ol.style.Stroke({
                    color: 'rgba(0, 0, 255, 1.0)',
                    width: 1
                }),
                fill: new ol.style.Fill({
                    color: gradRender.hexToRgbA(gradRender.classColors[classIndex], 0.7)
                })
            };
            textStyleConfig = {
                text: new ol.style.Text({
                    text: label,
                    font: '12px Calibri,sans-serif',
                    fill: new ol.style.Fill({
                        color: "#000000"
                    }),
                    stroke: new ol.style.Stroke({
                        color: "#FFFFFF",
                        width: 2
                    })
                }),
                geometry: function (feature) {
                    var retPoint;
                    if (feature.getGeometry().getType() === 'MultiPolygon') {
                        retPoint = gradRender.getMaxPoly(feature.getGeometry().getPolygons()).getInteriorPoint();
                    } else if (feature.getGeometry().getType() === 'Polygon') {
                        retPoint = feature.getGeometry().getInteriorPoint();
                    }

                    return retPoint;
                }
            }
        }
        ;

        var textStyle = new ol.style.Style(textStyleConfig);
        var style = new ol.style.Style(polyStyleConfig);
        return [style, textStyle];
    },
    getClassNum: function () {
        var elem = document.getElementById("classcount");
        return parseInt(elem.value);
        //return parseInt(5);
    },
    getMethod: function () {
        var elem = document.getElementById("methodselector");
        var val = elem.options[elem.selectedIndex].value;
        return val;
    },
    verifyClassFromVal: function (rangevals, val) {
        var retIndex = -1;
        for (var i = 0; i < rangevals.length; i++) {
            if (val >= rangevals[i].min && val <= rangevals[i].max) {
                retIndex = i;
            }
        }
        return retIndex;
    },
    hexToRgbA: function (hex, opacity) {
        var c;
        if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) {
            c = hex.substring(1).split('');
            if (c.length == 3) {
                c = [c[0], c[0], c[1], c[1], c[2], c[2]];
            }
            c = '0x' + c.join('');
            return 'rgba(' + [(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',') + ',' + opacity + ')';
        }
        throw new Error('Bad Hex');
    },
    getMaxPoly: function (polys) {
        var polyObj = [];
        //now need to find which one is the greater and so label only this
        for (var b = 0; b < polys.length; b++) {
            polyObj.push({
                poly: polys[b],
                area: polys[b].getArea()
            });
        }
        polyObj.sort(function (a, b) {
            return a.area - b.area
        });

        return polyObj[polyObj.length - 1].poly;
    },
    getCount: function (list, name, zoneNumber) {
        if (list.length == 0) {
            return 0;
        } else {
            var count = null;
            for (var i = 0; i < list.length; i++) {
                var item = list[i];
                if (zoneNumber == item.zoneNumber) {
                    count = item.count
                    break;
                } else {
                    count = 0
                }
            }
            return count;
        }
    },
    getCenter:function (id) {
        id = id.substring(0, 2);
        var center = null;
        var url = '../../assets/newMap/data/mapdata/city/' + id + '.json';
        $.ajax({
            url: url,
            type: 'GET',
            async: false,
            success: function (data) {
                center = ol.proj.transform(data.cp, 'EPSG:4326', 'EPSG:3857');
            }
        })
        return center;
    },
    reset:function (city) {
        if(this.vector != null){
            map.removeLayer(this.vector)
        }
        if(this.baseVector != null){
            map.removeLayer(this.baseVector)
        }
        this.baseVector = null;
        this.vector = null;
        this.source = null;
        this.classSeries = null;
        this.classColors = null;
        this.init(city);
        var center = this.getCenter(city);
        map.getView().setCenter(center);
    }
}